package Cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Callable;
@WebServlet("/CookieTest")
public class CookieTest extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");

        Cookie[] cookies = req.getCookies();
        boolean flag=false;
        if (cookies != null||cookies.length>0) {
            for (Cookie cookie:cookies) {
                String name = cookie.getName();
                if ("lastTime".equals(name)) {
                    flag=true;
                    Date date=new Date();
                    SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
                    String srt_date = sdf.format(date);
                    cookie.setValue(srt_date);
                    cookie.setMaxAge(60*60*24*30);
                    resp.addCookie(cookie);
                    String value = cookie.getValue();
                    resp.getWriter().write("<h1>欢迎回来，您上次访问的时间为"+value+"</h1>");
                    break;
                }
            }
        }
        if (cookies==null||cookies.length==0||flag==false) {
            Date date=new Date();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
            String srt_date = sdf.format(date);
            Cookie cookie=new Cookie("lastTime",srt_date);
            cookie.setMaxAge(60*60*24*30);
            resp.addCookie(cookie);

            resp.getWriter().write("<h1>您好,欢迎您首次访问</h1>");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}